﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Threading;
using Telerik.Framework.Search;
using Telerik.Events;
using Telerik.Cms.Engine;
using SelArom.Net.Sitefinity.API.Events;
using SelArom.Net.Sitefinity.API.Events.Data;

namespace SelArom.Net.Sitefinity.IndexProviders.GenericContent
{
	/// <summary>
	/// Indexes generic content items from the Default Provider for the Generic Content Module
	/// </summary>
	public class GenericContentIndexProvider : IIndexingServiceClient
	{
		/// <summary>
		/// Defines the name of the provider. This name is used to mange providers within Indexing Service.
		/// </summary>
		public string Name
		{
			get
			{
				return "Generic Content Index Provider";
			}
		}

		/// <summary>
		/// Provides detailed description of the client
		/// </summary>
		public string Description
		{
			get
			{
				return "Provides indexing for the all generic content modules.";
			}
		}

		public IIndexerInfo[] GetContentToIndex()
		{
			// init results
			var list = new List<IIndexerInfo>();

			// retrieve all GC Providers
			var providers = ContentManager.Providers;

			foreach (var provider in providers)
			{
				// skip non-GC providers
				if (provider.Value.GetType().FullName != "Telerik.Cms.Engine.Data.Providers.DefaultProvider") continue;

				// retrieve metakeys for this provider
				var MetaFields = provider.Value.MetaKeys;

				// parse provider items
				foreach (IContent cnt in new ContentManager(provider.Key).GetContent())
				{
					// init meta keys
					var metaFields = new Hashtable();
					foreach (var key in MetaFields)
					{
						// only index searchable keys
						if (key.Value.Searchable)
							metaFields.Add(key.Key, cnt.GetMetaData(key.Key));
					}

					// try alternate title if missing
					if (!metaFields.ContainsKey("Title") && metaFields.ContainsKey("Name")) metaFields.Add("Title", cnt.GetMetaData("Name"));

					// ensure url appkey is present and index item
					var cntUrl = ConfigurationManager.AppSettings[provider.Key + "Url"];
					if (string.IsNullOrEmpty(cntUrl)) break;
					var url = string.Concat(cntUrl, cnt.UrlWithExtension.ToLower());
					list.Add(
						new GenericContentIndexerInfo(
						url,
						metaFields,
						cnt.Content.ToString(),
						cnt.ID));
				}
			}
			return list.ToArray();
		}

		public string[] GetUrlsToIndex()
		{
			return new string[0];
		}

		public event EventHandler<IndexEventArgs> Index;

		public void Initialize(IDictionary<string, string> settings)
		{
		}
	}
}